package org.rebluh.hulunbuirtravelnetworkbackendframework.service;

import org.rebluh.hulunbuirtravelnetworkbackendframework.domain.EmailCode;
import org.rebluh.hulunbuirtravelnetworkbackendframework.domain.User;
import org.rebluh.hulunbuirtravelnetworkbackendframework.repository.EmailCodeRepository;
import org.rebluh.hulunbuirtravelnetworkbackendframework.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.nio.file.Files;
import java.util.List;
import java.util.Optional;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private EmailCodeRepository emailCodeRepository;
    @Autowired
    private MongoTemplate mongoTemplate;

    //添加用户
    public User createUser(User user) {
        return userRepository.save(user);
    }

    //根据邮箱获取用户
    public User findByUsermail(String email) {
        return userRepository.findByUsermail(email);
    }

    //根据id获取用户
    public Optional<User> getUserById(String id) {
        return userRepository.findById(id);
    }

    //获取全部用户
    public List<User> getAllUsers() {
        return userRepository.findAll();
    }

    //邮箱密码登录
    public Boolean verifyAccount(String email, String password) {
        User user = userRepository.findByUsermail(email);
        return email != null && user.getPassword().equals(password);
    }

    //邮箱验证码登录
    public Boolean verifyEmailCode(String email, String code) {
        // 获取邮箱的最新验证码
        EmailCode emailCodes = mongoTemplate.find(Query.query(Criteria.where("email").is(email)).with(Sort.by(Sort.Order.desc("time"))), EmailCode.class).get(0);
        if (code.equals(emailCodes.getCode())){
            // 查找是否为新用户
            if (mongoTemplate.find(Query.query(Criteria.where("usermail").is(email)), User.class).isEmpty()){
                // 创建用户
                User user = new User();
                user.setUsermail(email);
                user.setUsername(email);
                userRepository.save(user);
            }
            return true;
        }
        return false;
    }
}
